﻿using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi_SY.Entity;
using WebApi_SY.Models;

namespace WebApi_SY.Controllers
{
    [RoutePrefix("api/quality_model")]
    public class sli_qualityM_modelController : ApiController
    {
        

        // 创建质检模板
        [HttpPost, Route("create")]
        public async Task<IHttpActionResult> Create([FromBody] sli_quality_model model)
        {
            try
            {
                var _context = new YourDbContext();
                // 主表数据验证
                if (string.IsNullOrEmpty(model.Fformno))
                    return BadRequest("表单编号不能为空");

                var header = new sli_quality_model
                {
                    Fformid = model.Fformid,
                    Fformno = model.Fformno,
                    Fpartid = model.Fpartid,
                    Fpartno = model.Fpartno,
                    Fpartname = model.Fpartname,
                    Fqualityrank = model.Fqualityrank,
                    Fmateril = model.Fmateril,
                    Fsuppliername = model.Fsuppliername,
                    Finspectionquantity = model.Finspectionquantity,
                    sli_quality_modelentry = new List<sli_quality_modelentry>()
                };

                // 处理明细项
                if (model.sli_quality_modelentry?.Any() == true)
                {
                    foreach (var entry in model.sli_quality_modelentry)
                    {
                        header.sli_quality_modelentry.Add(new sli_quality_modelentry
                        {
                            Fformid = entry.Fformid,
                            Foptionid = entry.Foptionid,
                            Foptionname = entry.Foptionname,
                            Fitem = entry.Fitem,
                            Fno = entry.Fno,
                            Ftype = entry.Ftype,
                            Ftechnialrequirement = entry.Ftechnialrequirement,
                            Fmax = entry.Fmax,
                            Fmin = entry.Fmin,
                            //Factual = entry.Factual,
                            Fqualitytools = entry.Fqualitytools,
                            Fqualitytoolsname = entry.Fqualitytoolsname,
                            Serialnumber = entry.Serialnumber
                        });
                    }
                }

                _context.sli_quality_model.Add(header);
                await _context.SaveChangesAsync();

                return Ok(new
                {
                    code = 200,
                    msg = "模板创建成功",
                    modelId = header.Id
                });
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, new
                {
                    code = 500,
                    msg = "服务器错误",
                    error = ex.Message
                });
            }
        }

        // 分页查询模板列表
        [HttpGet, Route("list")]
        public IHttpActionResult GetPagedList(int page = 1, int pageSize = 10)
        {
            try
            {
                var _context = new YourDbContext();
                var query = _context.sli_quality_model
                    .OrderByDescending(m => m.Id)
                    .AsQueryable();

                var totalCount = query.Count();
                var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);

                var result = query
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .Select(m => new
                    {
                        m.Id,
                        m.Fformno,
                        m.Fpartno,
                        m.Fpartname,
                        m.Fqualityrank,
                        m.Fmateril,
                        m.Fsuppliername,
                        EntryCount = m.sli_quality_modelentry.Count
                    });

                return Ok(new
                {
                    code = 200,
                    data = new
                    {
                        total = totalCount,
                        pages = totalPages,
                        current = page,
                        pageSize,
                        list = result
                    }
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("detail/{Fformid}")]
        public IHttpActionResult GetDetail(int ? Fformid=0)
        {
            try
            {
                var _context = new YourDbContext();
               // IQueryable<sli_quality_model> query = await _context.sli_quality_model.Include(m => m.sli_quality_modelentry);
                var query = _context.sli_quality_model.Include(a => a.sli_quality_modelentry);
                //var result = await query.ToListAsync();

                if (Fformid.HasValue)
                {
                    query = query.Where(q => q.Fformid == Fformid.Value);
                }

                if (query == null)
                    return NotFound();

                var result =  query.Select(a => new
                {
                    Id=a.Id,
                    Fformid=a.Fformid,
                    Fformno = a.Fformno,
                    Fpartid = a.Fpartid,
                    Fpartno = a.Fpartno,
                    Fpartname = a.Fpartname,
                    Fqualityrank = a.Fqualityrank ?? string.Empty,
                    Fmateril = a.Fmateril ?? string.Empty,
                    a.Fsuppliername,
                    Finspectionquantity = a.Finspectionquantity??0,
                    Entries = a.sli_quality_modelentry.Select(e => new
                    {
                        Id=e.Id,
                        Foptionid=e.Foptionid,
                        Foptionname=e.Foptionname,
                        Fitem = e.Fitem,
                        Fno = e.Fno ?? string.Empty,
                        Ftype = e.Ftype ?? string.Empty,
                        Ftechnialrequirement = e.Ftechnialrequirement,
                        Fmax = e.Fmax,
                        Fmin = e.Fmin,
                        Factual = e.Factual,
                        Fqualitytools = e.Fqualitytools ?? 0,
                        Fqualitytoolsname=e.Fqualitytoolsname ?? string.Empty,
                        Serialnumber = e.Serialnumber ?? string.Empty
                    })
                });

                return Ok(new { code = 200, data = result });
            }
            catch (Exception ex)
            {
                // 实际生产环境应记录日志
                return InternalServerError(ex);
            }
        }

        // 更新模板
        [HttpPost]
        public async Task<IHttpActionResult> Update([FromBody] sli_quality_model model)
        {
            try
            {
                var _context = new YourDbContext();
                //var existing =  _context.sli_quality_model
                //    .Include(m => m.sli_quality_modelentry)
                //    .FirstOrDefaultAsync(m => m.Fformid == model.Fformid);

    //            var existing = _context.sli_quality_model
    //.Include(m => m.sli_quality_modelentry)
    //.FirstOrDefault(m => m.Fformid == model.Fformid);

                var existing = _context.sli_quality_model.FirstOrDefault(p => p.Id == model.Id);
                var existingentry = _context.sli_quality_modelentry.Where(p => p.Fformid == model.Id).ToList();

                if (existing == null )
                    return NotFound();

                // 更新主表信息
                //existing.Fformno = model.Fformno;
                //existing.Fpartid = model.Fpartid;
                //existing.Fpartno = model.Fpartno;
                //existing.Fpartname = model.Fpartname;
                //existing.Fqualityrank = model.Fqualityrank;
                //existing.Fmateril = model.Fmateril;
                //existing.Fsuppliername = model.Fsuppliername;
                //existing.Finspectionquantity = model.Finspectionquantity;

                // 安全更新主表字段（处理null值）
                existing.Fformno = model.Fformno ?? string.Empty;
                existing.Fpartid = model.Fpartid;
                existing.Fpartno = model.Fpartno ?? string.Empty;
                existing.Fpartname = model.Fpartname ?? string.Empty;
                existing.Fqualityrank = model.Fqualityrank ?? string.Empty;
                existing.Fmateril = model.Fmateril ?? string.Empty;
                existing.Fsuppliername = model.Fsuppliername ?? string.Empty;
                existing.Finspectionquantity = model.Finspectionquantity ?? 0;



                // 删除原有明细
                _context.sli_quality_modelentry.RemoveRange(existingentry);

                // 添加新明细
                foreach (var entry in model.sli_quality_modelentry)
                {
                    existing.sli_quality_modelentry.Add(new sli_quality_modelentry
                    {
                        Fformid = entry.Fformid,
                        Foptionid = entry.Foptionid,
                        Foptionname = entry.Foptionname ?? string.Empty,
                        Fitem = entry.Fitem ?? string.Empty,
                        Fno = entry.Fno ?? string.Empty,
                        Ftype = entry.Ftype ?? string.Empty,
                        Ftechnialrequirement = entry.Ftechnialrequirement ?? string.Empty,
                        Fmax = entry.Fmax,
                        Fmin = entry.Fmin,
                        Factual = entry.Factual ?? string.Empty,
                        Fqualitytools = entry.Fqualitytools ?? 0,
                        Fqualitytoolsname = entry.Fqualitytoolsname ?? string.Empty,
                        Serialnumber = entry.Serialnumber ?? string.Empty
                    });
                }

                await _context.SaveChangesAsync();

                return Ok(new
                {
                    code = 200,
                    msg = "模板更新成功"
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // 删除模板
        [HttpPost]
        public async Task<IHttpActionResult> Delete(int Fformid)
        {
            try
            {
                var _context = new YourDbContext();
                ////var model =  _context.sli_quality_model
                //    .Include(m => m.sli_quality_modelentry)
                //    .FirstOrDefault(m => m.Fformid == Fformid);

                var model = _context.sli_quality_model.FirstOrDefault(p => p.Id == Fformid);
                var modelentry = _context.sli_quality_modelentry.Where(p => p.Fformid == Fformid).ToList();

                if (model == null)
                    return NotFound();

                _context.sli_quality_modelentry.RemoveRange(model.sli_quality_modelentry);
                _context.sli_quality_model.Remove(model);

                await _context.SaveChangesAsync();

                return Ok(new
                {
                    code = 200,
                    msg = "模板删除成功"
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}